#!/usr/bin/env python
import compizconfig
import os
from xml.etree import cElementTree as ET
from lxml import etree
import sys
context = compizconfig.Context()


def CatSortCompare(v1, v2):
    if v1 == v2:
        return cmp(v1, v2)
    if context.Plugins['core'].Category == v1:
        return cmp('', v2 or 'zzzzzzzz')
    if context.Plugins['core'].Category == v2:
        return cmp(v1 or 'zzzzzzz', '')
    return cmp(v1 or 'zzzzzzzz', v2 or 'zzzzzzzz')

def FirstItemSortCompare(sg1, sg2):
    return cmp(sg1[0], sg2[0])
    
def PluginSortCompare(p1, p2):
    return cmp(p1.ShortDesc, p2.ShortDesc)
    
def SettingSortCompare(v1, v2):
    return cmp(v1.Plugin.Ranking[v1.Name], v2.Plugin.Ranking[v2.Name])
    
def fileExists(f):
     try:
         file = open(f)
     except IOError:
         exists = 0
     else:
         exists = 1
     return exists

def indent(elem, level=0):
    i = "\n" + level*"    "
    if len(elem):
        if not elem.text or not elem.text.strip():
            elem.text = i + "    "
        for e in elem:
            indent(e, level+1)
            if not e.tail or not e.tail.strip():
                e.tail = i + "    "
        if not e.tail or not e.tail.strip():
            e.tail = i
    else:
        if level and (not elem.tail or not elem.tail.strip()):
            elem.tail = i

if len(sys.argv) > 1:
    src = sys.argv[1]
else:
    src = sys.stdin

root = ET.Element("Everything")

def createXML():
	for categ in list(sorted(context.Categories, CatSortCompare)):
		if categ is '':
			categ = 'Unknown'
		nextCateg = ET.Element("Category", name=categ)
		root.append(nextCateg)
		for plugin in context.Categories[categ]:
			nextPlugin = plugin.xmlInfo
	#		nextPlugin.set("isEnabled", plugin.Enabled) 
	#		nextPlugin.set("hasIcon", fileExists('assets/icons/plugin-'+plugin.Name + '.png')) 
			nextCateg.append(nextPlugin)
			groupsSorted = sorted(plugin.Groups.items(), FirstItemSortCompare)
			for name, group in groupsSorted:
				if name is '':
					name = 'General'
				subGroupsSorted = sorted(group.items(), FirstItemSortCompare)
				nextGroup = ET.Element("Group", name=name)
				nextPlugin.append(nextGroup)
				for subGroupName, subGroup in subGroupsSorted:
					nextSubGroup = ET.Element("SubGroup", name=subGroupName)
					nextGroup.append(nextSubGroup)
					theSettings = sum((v.values() for v in [subGroup.Display]+[subGroup.Screens[0]]), [])
					theSettings = sorted(theSettings, SettingSortCompare)
					for setting in theSettings:
						nextSetting = setting.xmlInfo
						nextSubGroup.append(nextSetting)


def main():

	xml_file = os.path.abspath(__file__)
	xml_file = os.path.dirname(xml_file)
	xml_file = os.path.join(xml_file, "tester.xml")
	testerXML = open(xml_file, 'w') 
	
	createXML()
	
	tree = ET.ElementTree(root)
	indent(tree.getroot())
	
	tree.write(xml_file, encoding="utf-8",)
	


if __name__ == "__main__":
	main()


